// action ->  mutation -> state
import * as types from '../types'
import { asyncRouterMap, constantRouterMap } from '@/router/index/routes';
import { deepClone } from '@/utils/utils'

function hasPermission(roles, route) {
  if (route.meta && route.meta.role) {
    return roles.some(role => route.meta.role.indexOf(role) >= 0)
  } else {
    return true
  }
}

let _constantRouterMap = deepClone( constantRouterMap );
let _asyncRouterMap = deepClone( asyncRouterMap );

const state = {
  routers: _constantRouterMap,
  addRouters: []
}

const mutations = {
    [types.SET_ROUTERS](state, routers){
      state.addRouters = routers;
      state.routers = _constantRouterMap.concat(routers);
    }
}

const actions = {
  GenerateRoutes({ commit }, data) {
    return new Promise(resolve => {
      const { roles } = data;
      const accessedRouters = _asyncRouterMap.filter(v => {
        if (roles.indexOf('admin') >= 0) return true;
        if (hasPermission(roles, v)) {
          if (v.children && v.children.length > 0) {
            v.children = v.children.filter(child => {
              if (hasPermission(roles, child)) {
                return child
              }
              return false;
            });
            return v
          } else {
            return v
          }
        }
        return false;
      });
      commit(types.SET_ROUTERS, accessedRouters);
      resolve();
    })
  }
}

export default {
    state,
    mutations,
    actions
}
